package com.ruoyi.web.controller.pay;

import cn.hutool.core.date.DateUtil;
import cn.hutool.json.JSONArray;
import com.alibaba.fastjson2.JSON;
import com.ijpay.core.kit.WxPayKit;
import com.ruoyi.common.annotation.RepeatSubmit;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.page.TableDataInfo;
import com.ruoyi.common.utils.ip.IpUtils;
import com.ruoyi.order.domain.OrderInfo;
import com.ruoyi.order.domain.dto.OrderInfoAppPageDTO;
import com.ruoyi.order.domain.dto.OrderInfoDTO;
import com.ruoyi.order.service.IOrderInfoService;
import com.ruoyi.user.domain.AppUserAccount;
import com.ruoyi.user.service.IAppUserAccountService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * APP订单Controller
 *
 * @author ghostmen
 * @date 2024-11-03
 */
@Slf4j
@Validated
@RestController
@RequestMapping("/callBack")
@Api(value = "支付回调", tags = "支付回调接口")
public class CallBackController extends BaseController {

    @Autowired
    private IOrderInfoService orderInfoService;

    public static String SUCCESS = "SUCCESS";
    public static String FAIL = "FAIL";

    /**
     * 微信回调接口
     * https://pay.weixin.qq.com/wiki/doc/api/jsapi.php?chapter=9_7&index=8
     */
    @PostMapping("/wxPayNotice")
    public Map<String, String> parseOrderNotifyResult(@RequestBody String xmlData) throws ParseException {
        Map<String, String> map = new HashMap<>();
        log.info("微信回调开始了, 时间: {}", DateUtil.now());
        //这里我只进行了部分回调信息的保存，更多参数请查看微信支付官方api:https://pay.weixin.qq.com/wiki/doc/api/jsapi.php?chapter=9_7&index=8
        Map<String, String> resultMap = WxPayKit.xmlToMap(xmlData);
        /*----------------------分割线，下面的是业务代码，根据自己业务进行修改--------------------------*/

        log.info("微信回调响应参数: {}", JSON.toJSONString(resultMap));
        //订单成功业务处理
        if (!SUCCESS.equals(resultMap.get("result_code"))) {
            map.put("return_code", FAIL);
            return map;
        }
        String result = orderInfoService.parseOrderNotifyResult(resultMap);
        /*----------------------分割线，业务结束--------------------------*/
        log.info("微信回调结束了, 时间: {}", DateUtil.now());
        map.put("return_code", result);
        map.put("return_msg", SUCCESS.equals(result) ? "OK" : "");
        return map;
    }

}
